import { getDeviceInfo } from "@/utils/device";
import { sendHeartbeatApi } from '@/api/user';
import { ref } from "vue";

export async function sendHeartbeat(user_id:string, check_unique:boolean|null) {
    const ok = ref(true);
    const visitorId = ref('');
    const ip = ref('');
    const code = ref(100);

    try {
        console.log('heartbeat: send heartbeat to server');

        // 获取设备信息
        const deviceInfo = await getDeviceInfo();
        visitorId.value = deviceInfo.visitorId;
        ip.value = deviceInfo.ip;

        // 发送心跳请求
        const response = await sendHeartbeatApi({
            ip: deviceInfo.ip,
            visitorId: deviceInfo.visitorId,
            user_id: user_id,
            check_unique: check_unique
        });

        console.log("sendHeartbeatApi response: ", response);
        code.value = response.code;
        ok.value = response.code === 200;
        // if (response.data){
        //     console.log('heartbeat: response.data = ', response.)
        //     console.log('heartbeat: response.data = ', response.data);
        //     ok.value = false;
        // }
    } catch (error) {
        console.error('Error in sendHeartbeat:', error);
        ok.value = false;
    }

    console.log('heartbeat: ok = ', ok.value);

    return {
        code: code.value,
        ok: ok.value,
        visitorId: visitorId.value,
        ip: ip.value
    };
}
